using System;
using System.Collections.Generic;
using AutoInjector;
#if EASY_LOCALIZATION_TMP_SUPPORT
using TMPro;
#endif
using UnityEngine;
using UniRx;
using UnityEngine.UI;

namespace EasyLocalization
{
    public class LocalizationBinder : MonoBehaviour
    {
        [SerializeField, AutoInject] LocalizationDictionary _localizationDictionary;
        [SerializeField] Item[] _textItems;
#if EASY_LOCALIZATION_TMP_SUPPORT
        [SerializeField] Item[] _tmpItems;
#endif

        void Start()
        {
            Bind(_textItems, (text, s) => (text as Text).text = s);
#if EASY_LOCALIZATION_TMP_SUPPORT
            Bind(_tmpItems, (text, s) => (text as TextMeshProUGUI).SetText(s));
#endif
        }

        void Bind(IEnumerable<Item> items, Action<MaskableGraphic, string> setTextFn)
        {
            if (items == null)
            {
                return;
            }
            
            foreach (Item item in items)
            {
                _localizationDictionary.GetValueObservable(item.key)
                    .Subscribe(v => setTextFn(item.text, v))
                    .AddTo(this);
            }
        }

        [Serializable]
        public class Item
        {
            [SerializeField] MaskableGraphic _text;
            [SerializeField, LocalizationKey("_localizationDictionary", true)] string _key;
            public MaskableGraphic text => _text;
            public string key => _key;
        }
    }
}